package com.wstuo.common.tools.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.wstuo.common.tools.dao.ISMSRecordDAO;
import com.wstuo.common.tools.dto.SMSRecordDTO;
import com.wstuo.common.tools.entity.SMSRecord;
import com.wstuo.common.dto.PageDTO;
import com.wstuo.common.security.utils.AppContext;
import com.wstuo.common.security.utils.HtmlSpirit;

/**
 * 短信发送记录Service
 * @author QXY
 *
 */
public class SMSRecordService implements ISMSRecordService {
	
	
	@Autowired
	private ISMSRecordDAO smsRecordDAO;
	@Autowired
	private AppContext appctx;
	/**
	 * 分页查询信息记录.
	 */
	@SuppressWarnings("unchecked")
	@Transactional
	public PageDTO findPager(SMSRecordDTO qdto, int start,int limit, String sidx, String sord){
		PageDTO p=smsRecordDAO.findPager(qdto, start, limit, sidx, sord);
		List<SMSRecord> entitys=p.getData();
		List<SMSRecordDTO> dtos=new ArrayList<SMSRecordDTO>(entitys.size());
		for(SMSRecord entity:entitys){
			SMSRecordDTO dto=new SMSRecordDTO();
			entity.setContent(HtmlSpirit.delHTMLTag(entity.getContent()));
			SMSRecordDTO.entity2dto(entity, dto);
			dtos.add(dto);
		}
		p.setData(dtos);
		
		return p;
	}
	
	@Transactional
	public void save(SMSRecordDTO dto){
		SMSRecord entity=new SMSRecord();
		SMSRecordDTO.dto2entity(dto, entity);
		smsRecordDAO.save(entity);
		
	}
	
	@Transactional
	public void delete(Long [] ids){
		smsRecordDAO.deleteByIds(ids);
	}

	/**
	 * 保存历史信息.
	 * @param mobile 手机号码
	 * @param message 信息内容
	 * @param isSystem false为手动发送，true为系统发送
	 */
	@Transactional
	public void saveSMSHistory(String mobile,String message,boolean isSystem){
		//保存历史记录
		SMSRecord record=new SMSRecord();
		record.setMobile(mobile);
		record.setContent(message);
		record.setSendTime(new Date());
		if(isSystem){
			record.setSender("System");
		}else{
			//发送人 调试
			Object loginUserName=appctx.getCurrentLoginName();
			if(loginUserName!=null){
				record.setSender(loginUserName.toString());
			}
		}
		smsRecordDAO.save(record);
	}

}
